<template>
  <div class="query-form">
    <el-form
      :model="queryForm"
      ref="queryFormRef"
      label-width="100px"
      :inline="true"
    >
    <el-row>
      <el-col :span="8">
        <el-form-item label="供应商ID" label-width="150px" label-position="right">
        <el-input v-model="queryForm.venderId" placeholder="双击选择供应商" @dblclick="venderDialogVisible = true" style="width: 200px" />
      </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="供应商名称" label-width="150px" label-position="right">
        <el-input v-model="queryDto.venderName"  style="width: 200px" aria-disabled="true" readonly />
      </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="供应商编码" label-width="150px" label-position="right" >
        <el-input v-model="queryDto.venderOpcode"  style="width: 200px" aria-disabled="true" readonly />
      </el-form-item>
      </el-col>
    </el-row>


    <el-row>
      <el-col :span="8">
        <el-form-item label="商品ID" label-width="150px" label-position="right">
        <el-input v-model="queryForm.goodsId" placeholder="双击选择品种" @dblclick="goodsDialogVisible = true" style="width: 200px" />
      </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="商品名称" label-width="150px" label-position="right">
        <el-input v-model="queryDto.goodsName" placeholder=""  style="width: 200px" readonly />
      </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="商品编码" label-width="150px" label-position="right">
        <el-input v-model="queryDto.goodsOpcode" placeholder=""  style="width: 200px" readonly />
      </el-form-item>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="8">
        <el-form-item label="批号信息" label-width="150px" label-position="right">
        <el-input v-model="queryForm.lotNo" placeholder="请输入批号信息" style="width: 200px" />
      </el-form-item>
      </el-col>

      <el-col :span="8">
          <el-form-item label="联动日期" label-width="150px" label-position="right">
          <el-date-picker
            v-model="currentDate"
            type="daterange"
            range-separator="-"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
            style="width: 300px"
          />
          </el-form-item>
      </el-col>
<el-col :span="8">
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">清除</el-button>
            <el-button type="success" @click="handleBatchSave">申请</el-button>
          </el-form-item>
        </el-col>
    </el-row>

      <el-row>
        <el-col :span="8">
          <el-form-item label="合计可核销金额" label-width="150px" label-position="right">
        <el-input v-model="queryDto.actRebAmtTotal" placeholder="请勾选数据" style="width: 200px" readonly/>
      </el-form-item></el-col>
        <el-col :span="8"><el-form-item label="合计申请金额" label-width="150px" label-position="right">
        <el-input v-model="queryDto.rebAmtTotal" placeholder="请勾选数据" style="width: 200px" readonly/>
      </el-form-item></el-col>

      </el-row>
    </el-form>



















     <!-- 弹窗查询供应商 -->
    <el-dialog title="选择供应商" v-model="venderDialogVisible" width="700px">
      <el-row :gutter="10" style="margin-bottom: 10px;">
        <el-col :span="16">
          <el-input
            v-model="venderQuery"
            placeholder="请输入供应商名称"
            size="small"
          />
        </el-col>
        <el-col :span="1"/>
        <el-col :span="3">
          <el-button
            type="primary"
            size="small"
            style="width: 100%;"
            @click="venderSearch">
            查询
          </el-button>
        </el-col>
        <el-col :span="2"/>
      </el-row>

      <el-table
        :data="dataVender.list"
        style="width: 100%;"
        @row-click="selectvender">
        <el-table-column prop="comPartyId" label="供应商ID" width="120" />
        <el-table-column prop="partyOpcode" label="供应商代码" />
        <el-table-column prop="partyName" label="供应商名称" />
      </el-table>
       <!-- 分页 -->
      <div style="margin-top: 10px; text-align: right;">
        <el-pagination
          v-model:current-page="dataVender.pageNum"
          v-model:page-size="dataVender.pageSize"
          :total="dataVender.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="venderSearch"
          @current-change="venderSearch"
        />
      </div>
    </el-dialog>

    <!-- 弹窗查询品种 -->
    <el-dialog title="选择品种" v-model="goodsDialogVisible" width="700px">
      <el-row :gutter="10" style="margin-bottom: 10px;">
        <el-col :span="16">
          <el-input
            v-model="goodsQuery"
            placeholder="请输入品种信息"
            size="small"
          />
        </el-col>
        <el-col :span="1"/>
        <el-col :span="3">
          <el-button
            type="primary"
            size="small"
            style="width: 100%;"
            @click="goodsSearch">
            查询
          </el-button>
        </el-col>
        <el-col :span="2"/>
      </el-row>

      <el-table
        :data="dataGoods.list"
        style="width: 100%;"
        @row-click="selectGoods">
        <el-table-column prop="comGoodsId" label="品种ID" width="120" />
        <el-table-column prop="goodsOpcode" label="品种代码" />
        <el-table-column prop="goodsName" label="品种名称" />
        <el-table-column prop="goodsDesc" label="规格" />
        <el-table-column prop="productLocation" label="厂家" />
      </el-table>
       <!-- 分页 -->
      <div style="margin-top: 10px; text-align: right;">
        <el-pagination
          v-model:current-page="dataGoods.pageNum"
          v-model:page-size="dataGoods.pageSize"
          :total="dataGoods.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="goodsSearch"
          @current-change="goodsSearch"
        />
      </div>
    </el-dialog>
  </div>
  <div class="table-container">
    <el-table v-fit-columns
      :data="tableDataList.list"
      border
      style="width: 100%"
      :header-cell-style="{
        color: '#333',
        backgroundColor: '#eaf4ff',
        height: '20px'  // 表头固定高度
      }"
      @selection-change="handleSelectionChange"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '5px 0' }"
    >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="hnyyPurRebatePurListId" label="id" width="100" v-if="false"/>
        <el-table-column prop="hnyyPurRebatePurListId" label="id" width="100" v-if="false"/>
        <el-table-column prop="actRebAmt" label="可核销金额" width="100" />
        <el-table-column prop="totalApplyAmt" label="已申请金额" width="100" />
        <el-table-column label="申请金额" width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.applyAmt"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="purchaseNo" label="进仓单号" width="200" />
        <el-table-column prop="venderName" label="供应商名称" width="250" />
        <el-table-column prop="venderOpcode" label="供应商代码" width="120" />
        <el-table-column prop="receiverDate" label="收货日期" width="100" :formatter="formatDateHms"/>
        <el-table-column prop="goodsOpcode" label="商品编码" width="150" />
        <el-table-column prop="goodsName" label="商品名称" width="300" />
        <el-table-column prop="goodsDesc" label="商品规格" width="200" />
        <el-table-column prop="unitName" label="单位" width="60" />
        <el-table-column prop="qty" label="数量" width="60" />
        <el-table-column prop="taxPrice" label="含税单价" width="80" />
        <el-table-column prop="taxRate" label="税率" width="100" />
        <el-table-column prop="lotNoR" label="批号" width="150" />
        <el-table-column
          prop="produceDate"
          label="生产日期"
          width="100"
          :formatter="formatDate"
        />
        <el-table-column
          prop="expireDate"
          label="有效期"
          width="100"
          :formatter="formatDate"
        /><el-table-column
          prop="impDate"
          label="生成日期"
          width="100"
          :formatter="formatDate"
        />
        <el-table-column prop="comGoodsBatch" label="批次号" width="200" />

        <el-table-column prop="productLocation" label="生产厂家" width="300" />
        <el-table-column prop="channelOpcode" label="渠道号" width="100" />
        <el-table-column prop="chcanelName" label="渠道商" width="100" />
        <el-table-column prop="hnyyPurRebateListId" label="政策ID" width="90" />
        <el-table-column prop="checkerName" label="确权人" width="90" />
        <el-table-column
          prop="checkDate"
          label="确权时间"
          width="100"
          :formatter="formatDate"
        />
        <el-table-column prop="opFlagName" label="单据状态" width="90" />
      </el-table>
       <!-- 分页 -->
      <div style="margin-top: 10px; text-align: right;">
        <el-pagination
          v-model:current-page="tableDataList.pageNum"
          v-model:page-size="tableDataList.pageSize"
          :total="tableDataList.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>

  </div>
</template>
























<script setup>
import { reactive, ref,nextTick } from 'vue'
import request from '@/utils/request'
import { ElLoading,ElMessage  } from 'element-plus';
import {currentDate} from '../../utils/time.js';
import dayjs from 'dayjs'


const queryDto = reactive({})

const queryForm = reactive({
  venderId: '',
  goodsId:'',
  lotNo:'',
  opFlag:'ACCEPT',
  startDate: currentDate.value[0],
  endDate: currentDate.value[1],
  pageNum: 1,
  pageSize: 20
})
// 日期格式化
const formatDate = (row, column) => {
  const date = row[column.property]
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}
// 日期格式化
const formatDateHms = (row, column) => {
  const date = row[column.property]
  return date ? dayjs(date).format('YYYY-MM-DD HH:MM:DD') : ''
}
// 供应商弹窗
const venderDialogVisible = ref(false)

//品种弹窗
const goodsDialogVisible = ref(false)

// 供应商查询条件
const venderQuery = ref('')

// 品种查询条件
const goodsQuery = ref('')

// 主表单分页查询
const tableDataList = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list:[]
})

// 供应商分页查询
const dataVender = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list:[]
})

// 品种分页查询
const dataGoods = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list:[]
})

let loadingInstance = null;

const selectedRows = ref([]) // 存储勾选的行
const handleSelectionChange = (val) => {
  selectedRows.value = val
  // 计算合计
  let actTotal = 0
  let rebTotal = 0

  val.forEach(item => {
    actTotal += Number(item.actRebAmt) || 0
    rebTotal += Number(item.rebAmt) || 0
  })

  // 保留两位
  queryDto.actRebAmtTotal = Number(actTotal.toFixed(2))
  queryDto.rebAmtTotal = Number(rebTotal.toFixed(2))
}


// 供应商查询请求
const venderSearch = () => {
  if (!venderQuery.value) return ElMessage.warning('请输入供应商名称')
  nextTick(() => {
    loadingInstance = ElLoading.service({
      target: '.el-dialog__body',
      text: '加载中...'
    });
  });
  request.get('/link/getVenderList', { params: { name: venderQuery.value ,pageNum:dataVender.value.pageNum,pageSize:dataVender.value.pageSize} }).then((res) => {
    console.log('res=======> ', res)
    if (res.code === 200) {
      dataVender.value.list = res.data.list
      dataVender.value.total = res.data.total
    }
  }).catch((err) => {
      ElMessage.error('详情加载失败');
      console.error(err);
    }).finally(() => {
      if (loadingInstance) loadingInstance.close();
    });
}


// 品种查询请求
const goodsSearch = () => {
  if (!goodsQuery.value) return ElMessage.warning('请输入品种信息')
  nextTick(() => {
    loadingInstance = ElLoading.service({
      target: '.el-dialog__body',
      text: '加载中...'
    });
  });
  request.get('/link/getGoodsList', { params: { name: goodsQuery.value ,pageNum:dataGoods.value.pageNum,pageSize:dataGoods.value.pageSize} }).then((res) => {
    console.log('res=======> ', res)
    if (res.code === 200) {
      dataGoods.value.list = res.data.list
      dataGoods.value.total = res.data.total
    }
  }).catch((err) => {
      ElMessage.error('详情加载失败');
      console.error(err);
    }).finally(() => {
      if (loadingInstance) loadingInstance.close();
    });
}

// 供应商数据回填
const selectvender = (row) => {
  queryForm.venderId = row.comPartyId
  queryDto.venderName = row.partyName
  queryDto.venderOpcode = row.partyOpcode
  venderDialogVisible.value = false
}

// 品种数据回填
const selectGoods = (row) => {
  queryForm.goodsId = row.comGoodsId
  queryDto.goodsName = row.goodsName
  queryDto.goodsOpcode = row.goodsOpcode
  goodsDialogVisible.value = false
}


//主表单查询
const handleQuery = () => {
  console.log('queryForm',queryForm)
  if(queryForm.venderId==null||queryForm.venderId==''){
      ElMessage.error('请选择供应商')
        return
  }
  queryForm.startDate = dayjs(currentDate.value[0]).format('YYYY-MM-DD')
  queryForm.endDate = dayjs(currentDate.value[1]).format('YYYY-MM-DD')
  request.post('/account/getPurData', queryForm).then((res) => {
    console.log('res=======> ', res)
    if (res.code === 200) {
      tableDataList.list = res.data.list.map(item => {
        return {
          ...item,
          actRebAmt: item.actRebAmt == null || item.actRebAmt === '' ? item.rebAmt : item.actRebAmt
        }
      })
      tableDataList.total = res.data.total
      tableDataList.pageNum = res.data.pageNum
      tableDataList.pageSize = res.data.pageSize
    }

  }).catch((err) => {
      ElMessage.error('详情加载失败');
      console.error(err);
    });
}

//清除
const handleReset=()=>{
  Object.keys(queryForm).forEach(key=>{
      queryForm[key]=''

  })
  Object.keys(queryDto).forEach(key=>{
      queryDto[key]=''

  })
  queryForm.startDate = dayjs(currentDate.value[0]).format('YYYY-MM-DD')
  queryForm.endDate = dayjs(currentDate.value[1]).format('YYYY-MM-DD')
  queryForm.pageNum=1
  queryForm.pageSize=20
  queryForm.total=0
}

//申请
const handleBatchSave = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择要确权的数据')
    return
  }
  let d = []
  try {
    for (const row of selectedRows.value) {
        // 校验
      if(Number(row.applyAmt) < 0){
        ElMessage.error('申请金额不能小于0')
        row.applyAmt=0
         return
      }
      if (Number(row.applyAmt) > (Number(row.actRebAmt) - Number(row.totalApplyAmt))) {
        ElMessage.error('申请金额不能大于可申请金额-已申请金额，请重新填写')
        row.applyAmt=row.actRebAmt-row.totalApplyAmt
        return
      }
      d.push({hnyyPurRebatePurListId:row.hnyyPurRebatePurListId,applyAmt:row.applyAmt,venderPartyId:queryForm.venderId})
      // await handleSave(row)  // 等待每次请求完成
    }
    // 所有都执行完毕后再刷新
    request.post('/account/applyPur', d).then(res => {
    console.log('res',res)
    if (res.code === 200) {
      ElMessage.success('申请成功')
      handleQuery()
    } else {
      ElMessage.error('申请失败')
    }
  }).catch(err => {
    console.error(err)
    ElMessage.error('申请异常')
  })

  } catch (err) {
    console.error(err)
    ElMessage.error('批量申请过程中出现异常')
  }
}


</script>
